<template>
  <div class="container_box">
    <!--  <el-tag type="info" style="margin-left:1rem;">添加属性值,请先搜索,如果有选项,必须先选定再确认</el-tag> -->
    <el-row>
      <el-autocomplete
        v-model="singleInputAttributeName"
        :fetch-suggestions="querySearchAsyncAttributeName"
        placeholder="请输入内容"
        value-key="attribute_name"
        @select="handleSelectAttributeName"
      />
      <el-button style="margin-left:1rem;" type="primary" @click="handleAddCustomAttributeName()">添加自定义属性名</el-button>
    </el-row>
    <div v-if="systemAttributeNameList.length">
      <el-row v-for="(item,index) in systemAttributeNameList" :key="index" style="margin-top:0.5rem;">
        <div style="display:flex;flex-direction:row;">
          <el-tag type="info">{{ item.attribute_name }}</el-tag>
          <div v-if="!item.attributeValueArray || item.attributeValueArray.length === 0" class="attribute_value_array_box">
            暂无
          </div>
          <div v-if="item.attributeValueArray && item.attributeValueArray.length > 0" class="attribute_value_array_box">
            <el-tag v-for="(attributeValueItem,key) in item.attributeValueArray" :key="key" type="success" border size="medium"> {{ attributeValueItem.attribute_value }}</el-tag>
          </div>

          <div class="action_box">
            <div v-if="showGoodsAttributeNameId === item.goods_attribute_name_id && isShowInputAttributeValue" class="add_attribute_value_box">
              <el-autocomplete
                v-model="singleInputAttributeValue"
                style="width:200px;"
                :fetch-suggestions="querySearchAsyncAttributeValue"
                placeholder="请输入内容"
                value-key="attribute_value"
                @select="handleSelectAttributeValue"
              />
              <el-button style="margin-left:1rem;" type="primary" size="small" @click="handToConfirmAttributeValue(item)">确认</el-button>
              <el-button style="margin-left:1rem;" type="danger" size="small" @click="handToCancelAttributeValue(item)">取消</el-button>
            </div>
            <el-button v-if="!isShowInputAttributeValue" class="add_attribute_value_box" type="primary" size="small" @click="handToAddAttributeValue(item)">添加属性值</el-button>
          </div>
        </div>
      </el-row>
    </div>
    <div v-if="customAttributeNameList.length">
      <el-row v-for="(item,index) in customAttributeNameList" :key="index" style="margin-top:0.5rem;">
        <div style="display:flex;flex-direction:row;">
          <div style="display:flex;flex-direction:row;">
            <el-button type="warning" size="mini" @click="handleToRemoveCoustomAttributeName(item,index)">移除</el-button>
            <el-tag type="info">{{ item.attribute_name }}</el-tag>
          </div>
          <div v-if="!item.attributeValueArray || item.attributeValueArray.length === 0" class="attribute_value_array_box">
            暂无
          </div>
          <div v-if="item.attributeValueArray && item.attributeValueArray.length > 0" class="attribute_value_array_box">
            <el-tag v-for="(attributeValueItem,key) in item.attributeValueArray" :key="key" type="success" border size="medium"> {{ attributeValueItem.attribute_value }}</el-tag>
          </div>
          <div class="action_box">
            <div v-if="showGoodsAttributeNameId === item.id && isShowInputAttributeValue" class="add_attribute_value_box">
              <el-autocomplete
                v-model="singleInputAttributeValue"
                style="width:200px;"
                :fetch-suggestions="querySearchAsyncAttributeValue"
                placeholder="请输入内容"
                value-key="attribute_value"
                @select="handleSelectAttributeValue"
              />
              <el-button style="margin-left:1rem;" type="primary" size="small" @click="handToConfirmAttributeValue(item)">确认</el-button>
              <el-button style="margin-left:1rem;" type="danger" size="small" @click="handToCancelAttributeValue(item)">取消</el-button>
            </div>
            <el-button v-if="!isShowInputAttributeValue" class="add_attribute_value_box" type="primary" size="small" @click="handToAddAttributeValue(item)">添加属性值</el-button>
          </div>

        </div>
      </el-row>
    </div>
  </div>
</template>
<script>
import { getAllGoodsClassBindAttributeName, defaultGoodsAttributeName, findGoodsAttributeName, addCustomGoosAttributeName, defaultGoodsAttributeValue, findGoodsAttributeValue, addGoodsAttributeValue } from '@/api/youhu-shop/V1/goods/goodsAttribute'

export default
{
  // 组件名称
  name: 'GoodsAttribute',
  // 组件
  components:
  {

  },
  props:
    {
      // 产品分类id
      goodsClassId: {
        type: Number,
        default: null
      },
      // 系统属性名列表
      systemAttributeNameArray: {
        type: Array,
        default: function()
        {
          return []
        }
      },
      // 自定义属性名列表
      customAttributeNameArray: {
        type: Array,
        default: function()
        {
          return []
        }
      }
    },
  // 数据
  data()
  {
    return {
      // 系统属性名列表
      systemAttributeNameList: [],
      // 自定义属性名列表
      customAttributeNameList: [],
      // 单个输入的属性名
      singleInputAttributeName: null,
      // 建议输入属性名选项
      suggestAttributeNameList: [],
      // 属性名定时器
      attributeNameTimeout: null,
      // 选中的单个属性名
      selectSingleAttributeName: null,

      // 控制显示的属性名id
      showGoodsAttributeNameId: null,
      // 控制填写属性名值是否显示
      isShowInputAttributeValue: false,

      // 单个填写的属性值
      singleInputAttributeValue: null,
      // 建议输入属性值选项
      suggestAttributeValueList: [],
      // 属性值定时器
      attributeValueTimeout: null,
      // 选中的单个属性值
      selectSingleAttributeValue: null

    }
  },
  // 计算属性
  computed:
    {

    },
  // 监听
  watch:
  {

  },
  // 实例创建之前
  beforeCreate()
  {
  },
  // 创建
  created()
  {
  },
  // 挂载之前
  beforeMount()
  {
  },
  // 挂载 --常用
  mounted()
  {
    // console.log(this.goodsClassId)

    if (this.goodsClassId)
    {
      this.getAllGoodsClassBindAttributeName(this.goodsClassId)
      this.defaultGoodsAttributeName()
    }
  },
  // 更新之前
  beforeUpdate()
  {
  },
  // 跟新后
  updated()
  {
  },
  // 销毁之前
  beforeDestroy()
  {
  },
  // 销毁后
  destroyed()
  {
  },
  // 方法
  methods:
  {
    // 获取产品绑定的属性名
    async getAllGoodsClassBindAttributeName(goods_class_id)
    {
      const param = { goods_class_id: goods_class_id }
      let systemAttributeNameList = []
      systemAttributeNameList = await getAllGoodsClassBindAttributeName(param).then(res =>
      {
        return res.data
      })

      // console.log(systemAttributeNameList)
      this.systemAttributeNameList = systemAttributeNameList
    },
    async defaultGoodsAttributeName()
    {
      // const param = { limit: 10 }
      const param = { limit: 10 }
      // console.log(param)
      this.suggestAttributeNameList = await defaultGoodsAttributeName(param).then(res =>
      {
        // console.log(res)
        return res.data
      })
    },
    // 远程查询属性名
    async querySearchAsyncAttributeName(queryString, cb)
    {
      this.selectSingleAttributeName = null

      this.suggestAttributeNameList = await findGoodsAttributeName({ find: queryString, attribute_type: null }).then(res =>
      {
        return res.data
      })
      const suggestAttributeNameList = this.suggestAttributeNameList

      const results = queryString ? suggestAttributeNameList.filter(this.createSingleInputAttributeNameFilter(queryString)) : suggestAttributeNameList

      clearTimeout(this.attributeNametimeout)
      this.attributeNametimeout = setTimeout(() =>
      {
        cb(results)
      }, 1000 * Math.random())
    },
    // 过滤属性名
    createSingleInputAttributeNameFilter(queryString)
    {
      // console.log(queryString)

      return (singleInputAttributeName) =>
      {
        return (singleInputAttributeName.attribute_name.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    // 选择已有的属性名
    handleSelectAttributeName(item)
    {
      // console.log(item)
      this.selectSingleAttributeName = item
    },
    // 添加自定义属性名
    handleAddCustomAttributeName()
    {
      // c onsole.log(this.singleInputAttributeName)
      // console.log(this.selectSingleAttributeName)

      if (this.singleInputAttributeName && !this.selectSingleAttributeName)
      {
        addCustomGoosAttributeName({ attribute_name: this.singleInputAttributeName }).then(res =>
        {
          if (res && res.code === 0)
          {
            // console.log(res.data)
            this.customAttributeNameList.push(res.data)
          }
        })
      }

      if (this.singleInputAttributeName && this.selectSingleAttributeName)
      {
        this.customAttributeNameList.push(this.selectSingleAttributeName)
      }

      this.singleInputAttributeName = null
      this.selectSingleAttributeName = null
    },
    // 移除已有的属性名
    handleToRemoveCoustomAttributeName(item, index)
    {
      // console.log(item)

      if (Object.hasOwn(item, 'selectAttributeValueArray') && item.selectAttributeValueArray.length > 0)
      {
        this.$message.error('请先清除选中的属性值!')
      }
      else
      {
        const customAttributeNameList = this.customAttributeNameList
        customAttributeNameList.splice(index, 1)
        this.customAttributeNameList = customAttributeNameList
      }
      this.$emit('update:customAttributeNameArray', this.customAttributeNameList)
    },
    // 切换为添加属性值
    async handToAddAttributeValue(item)
    {
      // console.log('添加属性值')
      // console.log(item)

      // 系统的是 goods_attribute_name_id
      if (Object.hasOwn(item, 'goods_attribute_name_id'))
      {
        this.showGoodsAttributeNameId = item.goods_attribute_name_id
      }
      else
      {
        // 自定义的是id
        if (Object.hasOwn(item, 'id'))
        {
          this.showGoodsAttributeNameId = item.id
        }
      }

      this.isShowInputAttributeValue = true

      this.suggestAttributeValueList = await defaultGoodsAttributeValue({ goods_attribute_name_id: this.showGoodsAttributeNameId, limit: 10 }).then(res =>
      {
        return res.data
      })
    },
    // 远程查询属性值
    async querySearchAsyncAttributeValue(queryString, cb)
    {
      this.selectSingleAttributeValue = null

      this.suggestAttributeValueList = await findGoodsAttributeValue({ find: queryString, goods_attribute_name_id: this.showGoodsAttributeNameId }).then(res =>
      {
        return res.data
      })
      const suggestAttributeValueList = this.suggestAttributeValueList

      const results = queryString ? suggestAttributeValueList.filter(this.createSingleInputAttributeValueFilter(queryString)) : suggestAttributeValueList

      clearTimeout(this.attributeValuetimeout)
      this.attributeValuetimeout = setTimeout(() =>
      {
        cb(results)
      }, 1000 * Math.random())
    },
    // 过滤属性值
    createSingleInputAttributeValueFilter(queryString)
    {
      // console.log(queryString)

      return (singleInputAttributeValue) =>
      {
        return (singleInputAttributeValue.attribute_value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    // 选择已有的属性值
    handleSelectAttributeValue(attributeValueItem)
    {
      // console.log(item)
      this.selectSingleAttributeValue = attributeValueItem
    },
    // 确认添加属性值
    async handToConfirmAttributeValue(item)
    {
      // 检测该对象是否有属性值数组
      if (this.singleInputAttributeValue && !this.selectSingleAttributeValue)
      {
        let singleAttributeValue = null
        singleAttributeValue = await addGoodsAttributeValue({ attribute_value: this.singleInputAttributeValue, goods_attribute_name_id: this.showGoodsAttributeNameId }).then(res =>
        {
          if (res && res.code === 0)
          {
            return res.data
          }
        })

        if (singleAttributeValue)
        {
          if (Object.hasOwn(item, 'attributeValueArray'))
          {
            item.attributeValueArray.push(singleAttributeValue)
          }
          else
          {
            item['attributeValueArray'] = []
            item.attributeValueArray.push(singleAttributeValue)
          }
        }
      }

      if (this.singleInputAttributeValue && this.selectSingleAttributeValue)
      {
        if (Object.hasOwn(item, 'attributeValueArray'))
        {
          item.attributeValueArray.push(this.selectSingleAttributeValue)
        }
        else
        {
          item['attributeValueArray'] = []
          item.attributeValueArray.push(this.selectSingleAttributeValue)
        }
      }

      this.singleInputAttributeValue = null
      this.selectSingleAttributeValue = null
      this.showGoodsAttributeNameId = null
      this.isShowInputAttributeValue = false
      // console.log(this.systemAttributeNameList)
      // console.log(this.customAttributeNameList)
      this.$emit('update:systemAttributeNameArray', this.systemAttributeNameList)
      this.$emit('update:customAttributeNameArray', this.customAttributeNameList)
    },
    // 取消选择属性值
    handToCancelAttributeValue(item)
    {
      this.singleInputAttributeValue = null
      this.selectSingleAttributeValue = null
      this.showGoodsAttributeNameId = null
      this.isShowInputAttributeValue = false
    }

  }
}
</script>
<style lang='scss' scoped>
.container_box{
  width: auto;
  max-width: 80wh;
  overflow-x: scroll;
}
.attribute_value_array_box{
  display: flex;
  flex-direction: row;
  margin-left: 4rem;
  .attribute_value_item_box{
    display: flex;
    flex-direction: row;
    margin-left: 1rem;

  }
}
.action_box
{
  display: flex;
  flex-direction: row;
  margin-left: 2rem;
  .add_attribute_value_box{
    display: flex;
    flex-direction: row;
  }
}
</style>
